from django.conf import settings

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthUser
from oauth.serializers import QQOauthSerializers, WeiboOauthSerializers
from meiduo_mall.utils.weiboAndQQ import OAuthQQ, OAuthWeibo


class QQAuthURLLView(APIView):
    """定义QQ第三方登录的视图类"""
    def get(self, request):
        """
        获取QQ登录的链接
        :param request:
        :return:
        """
        # 1.通过查询字符串
        next = request.query_params.get('state')
        if not next:
            next = "/"

        # 获取QQ登录网页
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        login_url = oauth.get_qq_url()
        return Response({"login_url": login_url})

class QQOauthView(APIView):
    """验证QQ登录"""
    def get(self,request):
        """
        第三方登录检查
        :param request:
        :return:
        """
        # 1. 获取code值
        code = request.query_params.get("code")
        # 2.检查参数
        if not code:
            return Response({'errors': '缺少code值'}, status=400)

        # 3.通过code获取token值
        state = '/'
        # 创建qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state=state)
        access_token = qq.get_access_token(code=code)
        # print("access:%s" % access_token)
        # 4. 获取openid值
        openid = qq.get_open_id(access_token=access_token)
        print("openid:%s" % openid)
        # 5.判断是否绑定过美多账号
        try:
            qq_user = OAuthUser.objects.get(openid=openid)
        except:
            # 6.未绑定,进入绑定页面,完成绑定
            tjs = TJS(settings.SECRET_KEY, 300)
            open_id = tjs.dumps({'openid': openid}).decode()

            return Response({'access_token': open_id})
        else:
            # 7.绑定过,则登录成功
            # 生成jwt-token值
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)  # 生成载荷部分
            token = jwt_encode_handler(payload)  # 生成token

            response = Response(
                {
                    'token': token,
                    'username': user.username,
                    'user_id': user.id
                }
            )

            return response

    def post(self, request):
        """
        QQ绑定页面的请求,完成绑定用户操作
        :param request:
        :return:
        """
        # 1. 获取前端数据
        data = request.data
        # 2.调用序列化起验证数据
        ser = QQOauthSerializers(data=data)
        ser.is_valid()
        print(ser.errors)
        # 保存绑定数据
        ser.save()
        return Response(ser.data)



class WeiboAuthURLLView(APIView):
    """定义微博第三方登录的视图类"""
    def get(self, request):
        """
        获取微博登录的链接
        oauth/weibo/authorization/?next=/
        :param request:
        :return:
        """
        # 1.通过查询字符串
        next = request.query_params.get('state')
        if not next:
            next = "/"

        # 获取微博登录网页
        oauth = OAuthWeibo(client_id=settings.WEIBO_CLIENT_ID,
                        client_secret=settings.WEIBO_CLIENT_SECRET,
                        redirect_uri=settings.WEIBO_REDIRECT_URI,
                        state=next)
        login_url = oauth.get_weibo_url()
        return Response({"login_url": login_url})

class WeiboOauthView(APIView):
    """验证微博登录"""
    def get(self, request):
        """
        第三方登录检查
        oauth/sina/user/
        ?code=0e67548e9e075577630cc983ff79fa6a
        :param request:
        :return:
        """
        # 1.获取code值
        code = request.query_params.get("code")

        # 2.检查参数
        if not code:
            return Response({'errors': '缺少code值'}, status=400)

        # 3.获取token值
        next = "/"

        # 获取微博登录网页
        weiboauth = OAuthWeibo(client_id=settings.WEIBO_CLIENT_ID,
                        client_secret=settings.WEIBO_CLIENT_SECRET,
                        redirect_uri=settings.WEIBO_REDIRECT_URI,
                        state=next)
        weibotoken = weiboauth.get_access_token(code=code)
        print(weibotoken)

        # 5.判断是否绑定过美多账号
        try:
            weibo_user = OAuthUser.objects.get(weibotoken=weibotoken)
        except:
            # 6.未绑定,进入绑定页面,完成绑定
            tjs = TJS(settings.SECRET_KEY, 300)
            weibotoken = tjs.dumps({'weibotoken': weibotoken}).decode()

            return Response({'access_token': weibotoken})
        else:
            # 7.绑定过,则登录成功
            # 生成jwt-token值
            user = weibo_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)  # 生成载荷部分
            token = jwt_encode_handler(payload)  # 生成token

            response = Response(
                {
                    'token': token,
                    'username': user.username,
                    'user_id': user.id
                }
            )

        return response

    def post(self,request):
        """
        微博用户未绑定,绑定微博用户
        :return:
        """
        # 1. 获取前端数据
        data = request.data
        # 2.调用序列化起验证数据
        ser = WeiboOauthSerializers(data=data)
        ser.is_valid()
        print(ser.errors)
        # 保存绑定数据
        ser.save()
        return Response(ser.data)



